package com.cgy.utils.jmx.system.mem;

import com.cgy.utils.jmx.IJvmInfoFactory;
import com.cgy.utils.jmx.system.hardware.Hardware;

import java.util.Arrays;

import static oshi.hardware.CentralProcessor.TickType;

/**
 * @author CHTK
 */
public class CpuSystemFactory extends IJvmInfoFactory {

    private static final int PERCENT = 100;

    private static final Runtime runtime = Runtime.getRuntime();

    @Override
    public void status() {
        put("cpu.size", "" + runtime.availableProcessors(), "cpu个数");
        put("cpu.name", Hardware.PROCESSOR.getName(), "wcpu名称");
        put("cpu.vendor", Hardware.PROCESSOR.getVendor(), "cpu厂商");
        put("cpu.id", Hardware.PROCESSOR.getProcessorID(), "cpu id");

        long[] prevTicks = Hardware.PROCESSOR.getSystemCpuLoadTicks();
        long[] ticks = Hardware.PROCESSOR.getSystemCpuLoadTicks();

        System.out.println("CPU, IOWait, and IRQ ticks @ 1 sec:" + Arrays.toString(ticks));
        long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
        long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
        long sys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
        long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
        long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
        long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
        long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
        long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
        long totalCpu = user + nice + sys + idle + iowait + irq + softirq + steal;

        System.out.format(
                "User: %.1f%% Nice: %.1f%% System: %.1f%% Idle: %.1f%% IOwait: %.1f%% IRQ: %.1f%% SoftIRQ: %.1f%% Steal: %.1f%%%n",
                100d * user / totalCpu, 100d * nice / totalCpu, 100d * sys / totalCpu, 100d * idle / totalCpu,
                100d * iowait / totalCpu, 100d * irq / totalCpu, 100d * softirq / totalCpu, 100d * steal / totalCpu);
        System.out.format("CPU load: %.1f%% (counting ticks)%n", Hardware.PROCESSOR.getSystemCpuLoadBetweenTicks() * 100);

        put("cpu.os", "" + Hardware.PROCESSOR.getSystemCpuLoad() * 100, "系统使用率");

        double[] load = Hardware.PROCESSOR.getProcessorCpuLoadBetweenTicks();

        int count = 1;
        for (double avg : load) {
            int cnt = count++;
            put("cpu.per#" + cnt, String.format(" %.1f%%", avg * 100), "cpu#"+ cnt+"信息");
        }

    }



}
